package org.tio.http.client;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;
import org.tio.utils.SystemTimer;

/**
 * 
 * @author tanyaowu 
 * 2018年7月8日 上午11:12:21
 */
public class HttpClientAioHandler implements ClientAioHandler {
	private static Logger log = LoggerFactory.getLogger(HttpClientAioHandler.class);

	public static final String RESPONSE_KEY = "tio_response_key";

	/**
	 * @author tanyaowu
	 * 2016年11月18日 上午9:13:15
	 *
	 */
	public HttpClientAioHandler() {
	}

	@Override
	public ClientHttpResponse decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws AioDecodeException {
		ClientHttpResponse response = HttpResponseDecoder.decode(buffer, limit, position, readableLength, channelContext);
		channelContext.setAttribute(RESPONSE_KEY, response);
		return response;
	}

	@Override
	public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
		ClientHttpRequest request = (ClientHttpRequest) packet;
		ByteBuffer byteBuffer;
		try {
			byteBuffer = HttpRequestEncoder.encode(request, groupContext, channelContext);
			return byteBuffer;
		} catch (UnsupportedEncodingException e) {
			log.error(e.toString(), e);
			return null;
		}
	}

	public static AtomicLong count = new AtomicLong();
	@Override
	public void handler(Packet packet, ChannelContext channelContext) throws Exception {
//		ClientHttpResponse response = (ClientHttpResponse) packet;
		long c = count.incrementAndGet();
		if (c % HttpClientStarter.stepCount == 0) {
			System.out.println("已完成请求数：" + c);
		}
		if (c == HttpClientStarter.totalRequestCount) {
			long endtime = SystemTimer.currTime;
			long iv = endtime - HttpClientStarter.startTime;
			System.out.println("所有请求已经完成");
			System.out.println("客户端数：" + HttpClientStarter.clientCount);
			System.out.println("共完成请求数：" + c);
			System.out.println("总耗时：" + iv + "ms");
			System.out.println("平均每秒处理请求数：" + (1000 * (c / iv)));
		}
		
	}

	/** 
	 * @return
	 * @author tanyaowu
	 */
	@Override
	public Packet heartbeatPacket() {
		return null;
	}

}
